import React, {Component} from "react";
import {
    ActivityIndicator,
    Alert,
    InteractionManager,
    ListView,
    Modal,
    Text,
    TextInput,
    TouchableOpacity,
    View
} from "react-native";
import chjStyle from "../../../CustomStyle";
import ModuleCommonHeader from "../../module/ModuleCommonHeader";
import Util from "../../Util";
import {Actions} from "react-native-router-flux";
import {connect} from "react-redux";
import {setLoadingState} from "../../../redux/action/homePage.js";

const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
class CarSourceSelector extends Component {

    constructor(props) {
        super(props);
        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

        this.state = {
            isLoading: true,
            defaultPhone: '',
            defaultName: '',
            dataSource: ds.cloneWithRows([]),
            type: this.props.originType, /// type 1 是个人  type 2 是商家

            editorVisible: false,
            editType: this.props.originType,

            keyName: null,
            keyPhone: null,
        };
    }

    componentDidMount() {
        InteractionManager.runAfterInteractions(() => {
            this.setState({
                isLoading: false,
            });
            this.requestCarSourceList();
        });
    }

    renderRow(rowData) {
        let showThisRow = false;
        if (!this.state.keyName && !this.state.keyPhone) {
            showThisRow = true;
        }
        else if (this.state.keyName && rowData.source.indexOf(this.state.keyName) !== -1) {
            showThisRow = true;
        }
        else if (this.state.keyPhone && rowData.phone.indexOf(this.state.keyPhone) !== -1) {
            showThisRow = true;
        }
        else {
            showThisRow = false;
        }

        if (showThisRow)
            return (
                <TouchableOpacity style={chjStyle.textItem} onPress={
                    () => {
                        this.props.onSelectedListener(rowData);
                        console.log('CarSourceSelector  ' + rowData);
                        Actions.pop();
                    }
                }>
                    <Text style={{
                        position: 'absolute',
                        color: '#999',
                        textAlign: 'right',
                        backgroundColor: 'rgba(0, 0, 0, 0)',
                        fontSize: chjStyle.getActualFontSize(22),
                        left: chjStyle.getActualSizeInHorizontal(20),
                        top: chjStyle.getActualSizeInVertical(50)
                    }}>No.{rowData.sid}</Text>

                    <Text style={{
                        position: 'absolute',
                        color: '#333',
                        textAlign: 'right',
                        backgroundColor: 'rgba(0, 0, 0, 0)',
                        fontSize: chjStyle.getActualFontSize(28),
                        left: chjStyle.getActualSizeInHorizontal(120),
                        top: chjStyle.getActualSizeInVertical(44)
                    }}>{rowData.source}</Text>
                    <Text style={{
                        position: 'absolute',
                        color: '#25a',
                        textAlign: 'right',
                        backgroundColor: 'rgba(0, 0, 0, 0)',
                        fontSize: chjStyle.getActualFontSize(24),
                        right: chjStyle.getActualSizeInHorizontal(140),
                        top: chjStyle.getActualSizeInVertical(46)
                    }}>{rowData.phone}</Text>

                    <TouchableOpacity
                        onPress={() => this.editCarSource(rowData.sid, rowData.source, rowData.phone)}
                        style={{
                            position: 'absolute',
                            backgroundColor: '#0000',
                            top: chjStyle.getActualSizeInVertical(0),
                            right: chjStyle.getActualSizeInHorizontal(0),
                            width: chjStyle.getActualSizeInHorizontal(140),
                            height: chjStyle.getActualSizeInVertical(126),
                        }}><Text style={{
                        color: '#2a5',
                        textAlign: 'center',
                        top: chjStyle.getActualSizeInVertical(40),
                        fontSize: chjStyle.getActualFontSize(32)
                    }}>编辑</Text>
                    </TouchableOpacity>
                </TouchableOpacity>
            );
        else
            return null;
    }

    render() {
        if (this.state.isLoading) {
            return (
                <View
                    style={chjStyle.mainContainer}>
                    <ModuleCommonHeader title='车辆来源'/>
                    <ActivityIndicator
                        animating={true}
                        style={{alignItems: 'center', justifyContent: 'center', height: chjStyle.height}}
                        size="large"/>
                </View>);
        }
        return (
            <View
                style={chjStyle.mainContainer}>
                <ModuleCommonHeader title='车辆来源' leftText='取消'/>

                <TouchableOpacity
                    style={[chjStyle.textItem, {position: 'absolute', left: 0, top: chjStyle.headerHeight}]}>
                    <TextInput
                        ref='inputName'
                        editable={this.state.type === 2}
                        placeholder={this.state.type === 2 ? '商家名称' : '个人'}
                        maxLength={19}
                        onChangeText={(value) => this.onNameChangeText(value)}
                        underlineColorAndroid={'#00000000'}
                        defaultValue={this.state.type === 1 ? '个人' : this.state.defaultName}
                        style={{
                            position: 'absolute',
                            color: '#303030',
                            textAlign: 'left',
                            backgroundColor: 'rgba(0, 0, 0, 0)',
                            fontSize: chjStyle.getActualFontSize(30),
                            left: chjStyle.getActualSizeInHorizontal(30),
                            width: chjStyle.getActualSizeInHorizontal(690),
                            height: chjStyle.getActualSizeInVertical(128),
                        }}/>
                </TouchableOpacity>

                <TouchableOpacity
                    style={[chjStyle.textItem, {
                        position: 'absolute',
                        left: 0,
                        top: chjStyle.headerHeight + chjStyle.getActualSizeInVertical(128)
                    }]}>
                    <TextInput
                        ref='inputPhone'
                        placeholder={this.state.type === 2 ? '商家电话' : '个人电话'}
                        maxLength={11}
                        onChangeText={(value) => this.onPhoneChangeText(value)}
                        underlineColorAndroid={'#00000000'}
                        defaultValue={this.state.defaultPhone}
                        style={{
                            position: 'absolute',
                            color: '#303030',
                            textAlign: 'left',
                            backgroundColor: 'rgba(0, 0, 0, 0)',
                            fontSize: chjStyle.getActualFontSize(30),
                            left: chjStyle.getActualSizeInHorizontal(30),
                            width: chjStyle.getActualSizeInHorizontal(690),
                            height: chjStyle.getActualSizeInVertical(128),
                        }}/>
                </TouchableOpacity>

                <TouchableOpacity
                    onPress={() => this.createCarSource()}
                    style={{
                        position: 'absolute',
                        backgroundColor: '#1a1',
                        top: chjStyle.getActualSizeInVertical(424),
                        left: chjStyle.getActualSizeInHorizontal(125),
                        right: chjStyle.getActualSizeInHorizontal(0),
                        width: chjStyle.getActualSizeInHorizontal(500),
                        height: chjStyle.getActualSizeInVertical(88),
                        borderRadius: chjStyle.getActualSizeInHorizontal(44),
                    }}><Text style={{
                    color: '#fff',
                    backgroundColor: 'rgba(0,0,0,0)',
                    textAlign: 'center',
                    top: chjStyle.getActualSizeInVertical(22),
                    fontSize: chjStyle.getActualFontSize(32)
                }}>创建</Text>
                </TouchableOpacity>

                <TouchableOpacity
                    onPress={this.props.onClickedCreateListener}
                    style={[chjStyle.baseText, {
                        position: 'absolute',
                        backgroundColor: '#f91',
                        top: chjStyle.getActualSizeInVertical(582),
                        right: chjStyle.getActualSizeInHorizontal(0),
                        width: chjStyle.getActualSizeInHorizontal(750),
                        height: chjStyle.getActualSizeInVertical(60),
                    }]}><Text style={{
                    color: '#fff',
                    textAlign: 'center',
                    top: chjStyle.getActualSizeInVertical(10),
                    fontSize: chjStyle.getActualFontSize(30)
                }}>{this.state.type === 2 ? '商家列表' : '个人列表'}</Text>
                </TouchableOpacity>

                <ListView
                    ref="list"
                    style={{
                        position: 'absolute',
                        top: chjStyle.getActualSizeInVertical(642),
                        left: 0,
                        width: chjStyle.width,
                        height: chjStyle.getActualSizeInVertical(692)
                    }}
                    dataSource={this.state.dataSource}
                    renderRow={this.renderRow.bind(this)}
                />

                <Modal
                    animationType='fade'
                    transparent={true}
                    visible={this.state.editorVisible}
                    onRequestClose={() => {
                        this.setEditorVisible(false)
                    }}
                >
                    <TouchableOpacity
                        activeOpacity={1}
                        style={[chjStyle.mainContainer, {backgroundColor: 'rgba(0,0,0,0)'}]}
                        onPress={() => this.setEditorVisible(false)}>
                    </TouchableOpacity>

                    <View
                        style={[chjStyle.textItem, {position: 'absolute', left: 0, top: chjStyle.headerHeight}]}>
                        <TextInput
                            ref='editName'
                            editable={this.state.editType === 2}
                            placeholder={this.state.editType === 2 ? '请输入要修改的商家名称' : ''}
                            maxLength={19}
                            onChangeText={this.onEditNameChangeText.bind(this)}
                            underlineColorAndroid={'#00000000'}
                            defaultValue={this.state.editType === 2 ? this.state.editSource : '个人'}
                            style={{
                                position: 'absolute',
                                color: '#303030',
                                textAlign: 'left',
                                backgroundColor: 'rgba(0, 0, 0, 0)',
                                fontSize: chjStyle.getActualFontSize(30),
                                left: chjStyle.getActualSizeInHorizontal(30),
                                width: chjStyle.getActualSizeInHorizontal(690),
                                height: chjStyle.getActualSizeInVertical(128),
                            }}/>
                    </View>

                    <View
                        style={[chjStyle.textItem, {
                            position: 'absolute',
                            left: 0,
                            top: chjStyle.headerHeight + chjStyle.getActualSizeInVertical(128)
                        }]}>
                        <TextInput
                            ref='editPhone'
                            placeholder='请输入修改的电话'
                            maxLength={11}
                            onChangeText={this.onEditPhoneChangeText.bind(this)}
                            underlineColorAndroid={'#00000000'}
                            defaultValue={this.state.editPhone}
                            style={{
                                position: 'absolute',
                                color: '#303030',
                                textAlign: 'left',
                                backgroundColor: 'rgba(0, 0, 0, 0)',
                                fontSize: chjStyle.getActualFontSize(30),
                                left: chjStyle.getActualSizeInHorizontal(30),
                                width: chjStyle.getActualSizeInHorizontal(690),
                                height: chjStyle.getActualSizeInVertical(128),
                            }}/>
                    </View>

                    <TouchableOpacity
                        onPress={() => this.requestEditCarSource()}
                        activeOpacity={1}
                        style={{
                            position: 'absolute',
                            backgroundColor: '#11a',
                            top: chjStyle.getActualSizeInVertical(424),
                            left: chjStyle.getActualSizeInHorizontal(125),
                            right: chjStyle.getActualSizeInHorizontal(0),
                            width: chjStyle.getActualSizeInHorizontal(500),
                            height: chjStyle.getActualSizeInVertical(88),
                            borderRadius: chjStyle.getActualSizeInHorizontal(44),
                        }}><Text style={{
                        color: '#fff',
                        backgroundColor: 'rgba(0,0,0,0)',
                        textAlign: 'center',
                        top: chjStyle.getActualSizeInVertical(22),
                        fontSize: chjStyle.getActualFontSize(32)
                    }}>修改</Text>
                    </TouchableOpacity>
                </Modal>
            </View>
        );
    }

    onNameChangeText(value) {
        this.refs.inputName.value = value;
        this.setState({
            keyName: value,
            dataSource: ds.cloneWithRows(this.sourcelist),
        });
    }

    onPhoneChangeText(value) {
        this.refs.inputPhone.value = value;
        this.setState({
            keyPhone: value,
            dataSource: ds.cloneWithRows(this.sourcelist),
        });
    }

    onEditNameChangeText(value) {
        this.editName = value;
    }

    onEditPhoneChangeText(value) {
        this.editPhone = value;
    }

    // --- 请求 ---
    requestCarSourceList() {
        this.props.setLoading(true, '努力加载中...');
        const params = {
            type: this.state.type,
            userid: Util.getUser().id
        };
        Util.postServer('user/carsourcelist', params, (result) => this.onRequestListSuccess(result), (msg) => this.onRequestListFailed(msg));
    }

    onRequestListSuccess(result) {
        this.sourcelist = result.data.sourcelist;
        this.setState({
            dataSource: ds.cloneWithRows(result.data.sourcelist.reverse()),
        });
        this.props.setLoading(false, '');
    }

    onRequestListFailed(msg) {
        Alert.alert(msg);
        this.props.setLoading(false, '');
    }

    createCarSource() {
        if (!this.refs.inputName) {
            return;
        }
        if (!this.refs.inputPhone) {
            return;
        }
        if (this.state.type === 2 && !this.refs.inputName.value) {
            return;
        }
        if (!this.refs.inputPhone.value) {
            return;
        }

        if (this.state.type === 2 && this.refs.inputName.value.length < 2) {
            Alert.alert('请输入正确的商户名称');
            return;
        }
        if (this.refs.inputPhone.value.length < 11) {
            Alert.alert('请输入正确的手机号码');
            return;
        }
        this.props.setLoading(true, '努力加载中...');
        let params = {
            type: this.state.type,
            phone: this.refs.inputPhone.value,
            source: this.state.type === 2 ? this.refs.inputName.value : '个人'
        };
        Util.postServer('user/addcarsource', params, (result) => this.onCreateCSSuccess(result), (msg) => this.onCreateCSFailed(msg));
        this.setState({
            defaultName: '',
            defaultPhone: '',
        });
    }

    onCreateCSSuccess(result) {
        this.props.setLoading(false, '');
        this.requestCarSourceList();
    }

    onCreateCSFailed(msg) {
        this.props.setLoading(false, '');
        Alert.alert(msg);
    }

    editCarSource(sid, source, phone) {
        this.editName = source;
        this.editPhone = phone;
        this.setEditorVisible(true, sid, source, phone);
    }

    setEditorVisible(visible, sid, source, phone) {
        this.setState(
            {
                editorVisible: visible,
                editSid: sid,
                editSource: source,
                editPhone: phone
            }
        );
    }

    requestEditCarSource() {
        if (!this.editName || !this.editPhone) {
            return;
        }

        if (this.state.type === 2 && this.editName.length < 2) {
            Util.showToast('请输入正确的商户名称');
            return;
        }
        if (this.editPhone.length < 11) {
            Util.showToast('请输入正确的手机号码');
            return;
        }
        this.setEditorVisible(false);
        this.props.setLoading(true, '努力加载中...');
        const user = Util.getUser();
        let params = {
            sid: this.state.editSid,
            source: this.editName,
            phone: this.editPhone,
            userid: user.id,
            token: user.token,
        };
        Util.postServer('user/editcarsource', params, (result) => this.onEditCSSuccess(result), (msg) => this.onEditCSFailed(msg));
    }

    deleteCarSource(sid) {
        this.props.setLoading(true, '努力加载中...');
        const params = {
            sid: sid,
            userid: Util.user.userid
        };
        Util.postServer('user/delcarsource', params, (result) => this.onDeleteCSSuccess(result), (msg) => this.onDeleteCSFailed(msg));
    }

    onEditCSSuccess(result) {
        this.props.setLoading(false, '');
        this.requestCarSourceList();
    }

    onEditCSFailed(msg) {
        this.props.setLoading(false, '');
        Util.showToast(msg);
    }
}

const mapStateToProps = (state) => {
    return {};
};

const mapDispatchToProps = (dispatch) => {
    return {
        setLoading: (loading, text) => {
            dispatch(setLoadingState(loading, text));
        }
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(CarSourceSelector);


